package com.lez.flowpractice2.fragment

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import com.lez.flowpractice2.databinding.FragmentDownloadBinding
import com.lez.flowpractice2.download.DownloadManager
import com.lez.flowpractice2.download.DownloadStates
import kotlinx.coroutines.flow.collect
import java.io.File

/**
 * 下载实例,通过retrofit下载，返回一个flow数据流，结合emit和collect来显示下载进度
 */
class DownloadFragment : Fragment() {

    private val mBinding: FragmentDownloadBinding by lazy {
        FragmentDownloadBinding.inflate(layoutInflater)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?): View? {
        return mBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        //lifecycleScope生命周期跟随activity
        lifecycleScope.launchWhenCreated {
            context?.apply {
                var file = File(getExternalFilesDir(null),"pic.apk")
                DownloadManager.download("https://dl.jiaoliuqu.com/apk/taqu.apk",file).collect { downloadStates ->
                    when(downloadStates){
                       is DownloadStates.Progress -> {
                           //apply持有this对象，不返回this
                           mBinding.apply {
                               progressBar.progress = downloadStates.value
                               progressVal.text =  "${downloadStates.value}%"
                           }
                       }
                       is DownloadStates.Error -> {mBinding.progressVal.text = downloadStates.throwable.message}
                       is DownloadStates.Done -> {mBinding.progressVal.text = "下载完成"}
                    }
                }
            }
        }
    }
}